/**
 * FunCursor.java	  V1.0   Oct 13, 2011 11:53:13 AM
 *
 * Copyright 2011 AsiaInfo Linkage, All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package psn.ygn;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeoutException;


/**
 * 功能描述：
 *
 * @author  余根宁
 *
 * <p>修改历史：(修改人，修改时间，修改原因/内容)</p>
 */
public class FunCursor {
    
    private static ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory(){
        int nCount = 0;
        public Thread newThread(Runnable task){
            nCount ++;
            Thread invokeThread = new Thread(task);
            invokeThread.setName("Invoker-thread-"+nCount);
            //设置守护线程；
            invokeThread.setDaemon(true);
            return invokeThread;
        }
     });
    
    
    /**
     * 构造函数：
     *
     */
    public FunCursor() {

    }
    
    public static <T> Future<T> submit(Callable<T> task){
        Future<T> futureResult = executor.submit(task);
        return futureResult;
    }
    
    public static <T> T getFutureValue(Future<?> future)  throws TimeoutException{
        Object callRet = null;
        try{
            callRet = future.get();
        } catch(Exception err){
            if(err instanceof TimeoutException){
                throw new TimeoutException("invoke timeout!");
            }
            throw new RuntimeException(err);
        }
        
        return (T)callRet;
    }
    
    public static <T> T call(Callable<?> task) throws TimeoutException{
        Future<?> futureResult = executor.submit(task);
        Object callRet = null;
        try{
            callRet = futureResult.get();
        } catch(Exception err){
            if(err instanceof TimeoutException){
                throw new TimeoutException("invoke timeout!");
            }
            throw new RuntimeException(err);
        }
        
        return (T)callRet;
    }
}
